<template>
  <div class="app-container">
    <div class="detail-header">
      <el-page-header @back="goBack">
        <template #content>订单详情</template>
      </el-page-header>
    </div>

    <el-row :gutter="20" class="detail-content" v-loading="loading">
      <!-- 订单基本信息 -->
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
              <el-tag :type="statusFilter(orderInfo.status)">
                {{ statusTextFilter(orderInfo.status) }}
              </el-tag>
            </div>
          </template>
          <el-descriptions :column="3" border>
            <el-descriptions-item label="订单编号">
              {{ orderInfo.orderId }}
            </el-descriptions-item>
<<<<<<< HEAD
            <el-descriptions-item label="创建时间">
              {{ orderInfo.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              ¥{{ orderInfo.totalAmount?.toFixed(2) }}
            </el-descriptions-item>
            <el-descriptions-item label="支付方式">
              {{ orderInfo.paymentMethod }}
            </el-descriptions-item>
            <el-descriptions-item label="支付时间">
              {{ orderInfo.paymentTime }}
            </el-descriptions-item>
            <el-descriptions-item label="支付状态">
              {{ orderInfo.paymentStatus }}
=======
            <el-descriptions-item label="下单时间">
              {{ orderInfo.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="订单金额">
              <span class="amount">¥{{ orderInfo.totalAmount?.toFixed(2) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="服务类型">
              <el-tag :type="getServiceTypeColor(orderInfo.serviceType)">
                {{ orderInfo.serviceType }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="预约时间">
              {{ orderInfo.appointmentTime }}
            </el-descriptions-item>
            <el-descriptions-item label="距离">
              {{ orderInfo.distance }}km
            </el-descriptions-item>
            <el-descriptions-item label="客户姓名">
              {{ orderInfo.customerName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ orderInfo.customerPhone }}
              <el-button type="primary" link size="small" @click="callCustomer">
                <el-icon><Phone /></el-icon>
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="特殊要求">
              {{ orderInfo.specialNote || '无' }}
>>>>>>> c61637f (所有前后端正常登录)
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

<<<<<<< HEAD
      <!-- 收货信息 -->
=======
      <!-- 取件配送信息 -->
>>>>>>> c61637f (所有前后端正常登录)
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
<<<<<<< HEAD
              <span>收货信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收货人">
              {{ orderInfo.receiverName }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ orderInfo.receiverPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">
              {{ orderInfo.receiverAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ orderInfo.remark || '无' }}
=======
              <span>取件配送信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="取件地址" :span="2">
              {{ orderInfo.pickupAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="配送地址" :span="2">
              {{ orderInfo.deliveryAddress || orderInfo.pickupAddress }}
            </el-descriptions-item>
            <el-descriptions-item label="取件时间">
              {{ orderInfo.pickupTime || '待安排' }}
            </el-descriptions-item>
            <el-descriptions-item label="配送时间">
              {{ orderInfo.deliveryTime || '待安排' }}
            </el-descriptions-item>
            <el-descriptions-item label="取件员">
              {{ orderInfo.pickupStaff || '待分配' }}
            </el-descriptions-item>
            <el-descriptions-item label="配送员">
              {{ orderInfo.deliveryStaff || '待分配' }}
>>>>>>> c61637f (所有前后端正常登录)
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>

<<<<<<< HEAD
      <!-- 商品信息 -->
=======
      <!-- 洗护物品信息 -->
>>>>>>> c61637f (所有前后端正常登录)
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
<<<<<<< HEAD
              <span>商品信息</span>
            </div>
          </template>
          <el-table :data="orderInfo.items" style="width: 100%">
            <el-table-column prop="goodsId" label="商品ID" width="180" />
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="price" label="单价">
              <template #default="scope">
                ¥{{ scope.row.price.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column label="小计">
              <template #default="scope">
                ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
=======
              <span>洗护物品清单</span>
            </div>
          </template>
          <el-table :data="orderInfo.items" style="width: 100%">
            <el-table-column prop="name" label="物品名称" width="150" />
            <el-table-column prop="category" label="类别" width="100">
              <template #default="scope">
                <el-tag size="small">{{ scope.row.category }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="condition" label="物品状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.condition === '正常' ? 'success' : 'warning'" size="small">
                  {{ scope.row.condition }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.price?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="100">
              <template #default="scope">
                <span class="amount">¥{{ (scope.row.price * scope.row.quantity)?.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="note" label="备注" min-width="150" />
>>>>>>> c61637f (所有前后端正常登录)
          </el-table>
          <div class="order-total">
            <span>订单总额：</span>
            <span class="price">¥{{ orderInfo.totalAmount?.toFixed(2) }}</span>
          </div>
        </el-card>
      </el-col>

      <!-- 订单状态记录 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单状态记录</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in orderInfo.statusHistory"
              :key="index"
              :timestamp="activity.time"
              :type="activity.type"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <!-- 操作按钮 -->
      <el-col :span="24" class="mt-20">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单操作</span>
            </div>
          </template>
          <div class="operation-buttons">
            <el-button
<<<<<<< HEAD
              v-if="orderInfo.status === 'pending'"
              type="primary"
              @click="handleConfirmOrder"
            >
              确认订单
            </el-button>
            <el-button
              v-if="orderInfo.status === 'pending'"
              type="danger"
=======
              v-if="orderInfo.status === ORDER_STATUS.PENDING"
              type="primary"
              size="large"
              @click="handleConfirmPayment"
            >
              确认付款
            </el-button>
            <el-button
              v-if="orderInfo.status === ORDER_STATUS.PAID"
              type="success"
              size="large"
              @click="handleShipOrder"
            >
              发货
            </el-button>
            <el-button
              v-if="orderInfo.status === ORDER_STATUS.SHIPPED"
              type="info"
              size="large"
              @click="handleConfirmDelivery"
            >
              确认送达
            </el-button>
            <el-button
              v-if="orderInfo.status === ORDER_STATUS.DELIVERED"
              type="warning"
              size="large"
              @click="handleFinishOrder"
            >
              完成订单
            </el-button>
            <el-button
              v-if="[ORDER_STATUS.PENDING, ORDER_STATUS.PAID].includes(orderInfo.status)"
              type="danger"
              size="large"
>>>>>>> c61637f (所有前后端正常登录)
              @click="handleCancelOrder"
            >
              取消订单
            </el-button>
            <el-button
<<<<<<< HEAD
              v-if="orderInfo.status === 'processing'"
              type="success"
              @click="handleCompleteOrder"
            >
              完成订单
=======
              size="large"
              @click="callCustomer"
            >
              联系客户
>>>>>>> c61637f (所有前后端正常登录)
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
<<<<<<< HEAD
import { getOrderDetail, updateOrderStatus, cancelOrder } from '@/api/orders'
=======
import {
  getOrderDetail,
  updateOrderStatus,
  cancelOrder,
  ORDER_STATUS,
  ORDER_STATUS_TEXT,
  ORDER_STATUS_COLOR
} from '@/api/orders'
>>>>>>> c61637f (所有前后端正常登录)

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const orderInfo = ref({})

<<<<<<< HEAD
// 状态过滤器
const statusFilter = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status]
}

// 状态文本过滤器
const statusTextFilter = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status]
=======
// 状态过滤器（使用后端真实状态）
const statusFilter = (status) => {
  return ORDER_STATUS_COLOR[status] || 'info'
}

// 状态文本过滤器（使用后端真实状态）
const statusTextFilter = (status) => {
  return ORDER_STATUS_TEXT[status] || '未知状态'
}

// 获取服务类型颜色
const getServiceTypeColor = (serviceType) => {
  const colorMap = {
    '精洗套装': 'primary',
    '普通清洗': 'success',
    '干洗': 'warning',
    '快洗': 'info',
    '洗鞋': 'primary',
    '洗萌宠': 'warning',
    '洗包包': 'success',
    '洗被子': 'info',
    '洗车': 'primary',
    '上门清洗': 'warning',
    '疏通厕所': 'danger'
  }
  return colorMap[serviceType] || 'info'
}

// 拨打客户电话
const callCustomer = () => {
  ElMessage.info(`正在拨打客户电话：${orderInfo.value.customerPhone}`)
>>>>>>> c61637f (所有前后端正常登录)
}

// 获取订单详情
const getOrderInfo = async () => {
  try {
    loading.value = true
    const orderId = route.params.id
<<<<<<< HEAD
    const res = await getOrderDetail(orderId)
    orderInfo.value = res.data
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
=======
    const response = await getOrderDetail(orderId)

    if (response.code === 200) {
      orderInfo.value = response.data
    } else {
      throw new Error(response.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error(error.message || '获取订单详情失败')

    // 如果API失败，使用模拟数据
    if (import.meta.env.DEV) {
      console.warn('API失败，使用模拟数据')
      orderInfo.value = getMockOrderDetail()
    }
>>>>>>> c61637f (所有前后端正常登录)
  } finally {
    loading.value = false
  }
}

<<<<<<< HEAD
// 确认订单
const handleConfirmOrder = async () => {
  try {
    await ElMessageBox.confirm('确认要接受此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await updateOrderStatus(orderInfo.value.orderId, 'processing')
    ElMessage.success('订单已确认')
    getOrderInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认订单失败:', error)
      ElMessage.error('确认订单失败')
=======
// 获取空的订单详情数据
const getMockOrderDetail = () => {
  return {
    id: route.params.id,
    orderId: '',
    orderNo: '',
    status: ORDER_STATUS.PENDING,
    totalAmount: 0,
    actualAmount: 0,
    serviceType: '',
    createTime: '',
    customerName: '',
    customerPhone: '',
    pickupAddress: '',
    deliveryAddress: '',
    appointmentTime: '',
    distance: 0,
    specialNote: '',
    items: [],
    statusHistory: []
  }
}

// 确认付款
const handleConfirmPayment = async () => {
  try {
    await ElMessageBox.confirm('确认客户已付款？', '确认付款', {
      confirmButtonText: '确认付款',
      cancelButtonText: '取消',
      type: 'info'
    })

    const response = await updateOrderStatus(orderInfo.value.id, {
      status: ORDER_STATUS.PAID,
      remark: '商家确认客户已付款'
    })

    if (response.code === 200) {
      ElMessage.success('付款确认成功！')
      getOrderInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认付款失败:', error)
      ElMessage.error('确认付款失败')
    }
  }
}

// 发货
const handleShipOrder = async () => {
  try {
    const { value: trackingNumber } = await ElMessageBox.prompt(
      '请输入物流单号',
      '发货',
      {
        confirmButtonText: '确认发货',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入物流单号',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入物流单号'
          }
          return true
        }
      }
    )

    const response = await updateOrderStatus(orderInfo.value.id, {
      status: ORDER_STATUS.SHIPPED,
      trackingNumber: trackingNumber.trim(),
      remark: '商家已发货'
    })

    if (response.code === 200) {
      ElMessage.success('发货成功！')
      getOrderInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发货失败:', error)
      ElMessage.error('发货失败')
    }
  }
}

// 确认送达
const handleConfirmDelivery = async () => {
  try {
    await ElMessageBox.confirm('确认商品已送达？', '确认送达', {
      confirmButtonText: '确认送达',
      cancelButtonText: '取消',
      type: 'success'
    })

    const response = await updateOrderStatus(orderInfo.value.id, {
      status: ORDER_STATUS.DELIVERED,
      remark: '商家确认商品已送达'
    })

    if (response.code === 200) {
      ElMessage.success('送达确认成功！')
      getOrderInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认送达失败:', error)
      ElMessage.error('确认送达失败')
    }
  }
}

// 完成订单
const handleFinishOrder = async () => {
  try {
    await ElMessageBox.confirm('确认完成订单？', '完成订单', {
      confirmButtonText: '确认完成',
      cancelButtonText: '取消',
      type: 'success'
    })

    const response = await updateOrderStatus(orderInfo.value.id, {
      status: ORDER_STATUS.FINISHED,
      remark: '订单已完成'
    })

    if (response.code === 200) {
      ElMessage.success('订单完成！')
      getOrderInfo()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
>>>>>>> c61637f (所有前后端正常登录)
    }
  }
}

// 取消订单
const handleCancelOrder = async () => {
  try {
<<<<<<< HEAD
    await ElMessageBox.confirm('确认要取消此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    })
    
    await cancelOrder(orderInfo.value.orderId)
    ElMessage.success('订单已取消')
    getOrderInfo()
=======
    const { value: reason } = await ElMessageBox.prompt(
      '确认取消订单？',
      '取消订单',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入取消原因',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) {
            return '请输入取消原因'
          }
          return true
        }
      }
    )

    const response = await cancelOrder(orderInfo.value.id, { reason })

    if (response.code === 200) {
      ElMessage.success('订单已取消')
      getOrderInfo()
    }
>>>>>>> c61637f (所有前后端正常登录)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

<<<<<<< HEAD
// 完成订单
const handleCompleteOrder = async () => {
  try {
    await ElMessageBox.confirm('确认要完成此订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    await updateOrderStatus(orderInfo.value.orderId, 'completed')
    ElMessage.success('订单已完成')
    getOrderInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成订单失败:', error)
      ElMessage.error('完成订单失败')
    }
  }
}

=======
>>>>>>> c61637f (所有前后端正常登录)
// 返回列表
const goBack = () => {
  router.push('/orders')
}

// 初始化
onMounted(() => {
  getOrderInfo()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.detail-header {
  margin-bottom: 20px;
}

.detail-content {
  margin-top: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-total {
  margin-top: 20px;
  text-align: right;
  padding-right: 20px;
}

.order-total .price {
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
  margin-left: 10px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
<<<<<<< HEAD
  gap: 20px;
=======
  gap: 15px;
  flex-wrap: wrap;
  margin-top: 20px;
}

.amount {
  color: #059669;
  font-weight: bold;
}

:deep(.el-card) {
  border-radius: 8px;
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-descriptions-item__label) {
  font-weight: 500;
}

:deep(.el-table) {
  font-size: 14px;
>>>>>>> c61637f (所有前后端正常登录)
}
</style>